#include "AnalogClock.h"

#include <QPainter>
#include <QTimer>
#include <QTime>

AnalogClock::AnalogClock(QWidget *parent)
    : QWidget(parent)
{

//建立信号槽 每一秒调用一次update
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(1000);
    setWindowTitle(tr("Analog Clock"));
    resize(200, 200);
}

AnalogClock::~AnalogClock()
{

}


void AnalogClock::paintEvent(QPaintEvent *event)
{
    //时针图形坐标
    static const QPoint hourHand[3] = {
        QPoint(7, 8),
        QPoint(-7, 8),
        QPoint(0, -40)
    };


    //分针图形坐标
    static const QPoint minuteHand[3] = {
        QPoint(7, 8),
        QPoint(-7, 8),
        QPoint(0, -70)
    };

    //秒针图形坐标
    static const QPoint secondHand[3] = {
        QPoint(6, 7),
        QPoint(-6, 7),
        QPoint(0, -90)
    };

    //时针分针颜色
    QColor hourColor(127, 0, 127);
    QColor minuteColor(0, 127, 127, 191);
    QColor secondColor(0, 0, 0);

    int side = qMin(width(), height());
    QTime time = QTime::currentTime();

//painter
    QPainter painter(this);
    // 反走样
    painter.setRenderHint(QPainter::Antialiasing);
    painter.translate(width() / 2, height() / 2);
    painter.scale(side / 200.0, side / 200.0);


    //设置时针 画刷
    painter.setPen(Qt::NoPen);
    painter.setBrush(hourColor);
    painter.save();

    //绘制时针
    painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
    painter.drawConvexPolygon(hourHand, 3);
    painter.restore();


    //设置时针刻度盘颜色
    painter.setPen(hourColor);

    //绘制时针刻度盘
    for (int i = 0; i < 12; ++i) {
        painter.drawLine(88, 0, 96, 0);
        painter.rotate(30.0);
    }

    //绘制分针
    painter.setPen(Qt::NoPen);
    painter.setBrush(minuteColor);
    painter.save();
    painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
    painter.drawConvexPolygon(minuteHand, 3);
    painter.restore();

    //设置分针刻度盘颜色
    painter.setPen(minuteColor);

    //绘制分针刻度盘
    for (int j = 0; j < 60; ++j) {
        if ((j % 5) != 0)
            painter.drawLine(92, 0, 96, 0);
        painter.rotate(6.0);
    }

    //绘制秒针
    painter.setPen(Qt::NoPen);
    painter.setBrush(secondColor);
    painter.save();
    painter.rotate(6.0 * (time.second()));
    painter.drawConvexPolygon(secondHand, 3);
    painter.restore();

    //绘制时间刻度盘
    painter.setPen(Qt::SolidLine);
    painter.drawText(0,-68,QString::number(0));
    painter.drawText(0, 68,QString::number(3));
    painter.drawText(68,0,QString::number(6));
    painter.drawText(-68,0,QString::number(9));

    painter.restore();

}
